//
//  VCForClickZhuanTiCell.m
//  
//
//  Created by dllo on 16/1/26.
//
//

#import "VCForClickZhuanTiCell.h"
#import "HeaderOfClickZhuanTiCell.h"
#import "CellForClickZhuanTiCell.h"
#import "PCH.pch"
#import "ModelOfClickZhuanTiCell.h"
#import "ModelForClickZTOfArticle.h"
#import "CellForClickZhuanTiCell2.h"
#import "DataBaseHandler.h"
#import "VCOfPhoto.h"
#import <UIImageView+WebCache.h>


#import <CommonCrypto/CommonDigest.h>
#import "Reachability.h"

@interface VCForClickZhuanTiCell () <UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, retain)UITableView *tableView;
@property (nonatomic, retain)ModelOfClickZhuanTiCell *model;
@property (nonatomic, retain)NSMutableArray *arrayOfModelForCell;
@property (nonatomic, retain)UIButton *buttonOfLeft;
@property (nonatomic, retain)UIButton *buttonOfRight;

@property (nonatomic, assign)CGFloat lastContentOffset;

@end

@implementation VCForClickZhuanTiCell

- (void)dealloc {
    self.tableView.delegate = nil;
    self.tableView.dataSource = nil;
    [_id release];
    [_buttonOfLeft release];
    [_buttonOfRight release];
    [_arrayOfModelForCell release];
    [_tableView release];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"passPhoto" object:nil];
    [super dealloc];
}

- (void)viewWillAppear:(BOOL)animated {
    self.tabBarController.tabBar.hidden = YES;

}

- (void)viewWillDisappear:(BOOL)animated {
    self.tabBarController.tabBar.hidden = NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self panDuanWangLuo];
    
    self.view.backgroundColor = [UIColor whiteColor];
    self.arrayOfModelForCell = [NSMutableArray array];
    
   // self.navigationController.navigationBar.translucent = YES;
    
    /** 主页navigation左侧button */
    self.buttonOfLeft = [UIButton buttonWithType:UIButtonTypeCustom];
    self.buttonOfLeft.frame = CGRectMake(5, 10, 30, 30);
    [self.buttonOfLeft addTarget:self action:@selector(fanHui:) forControlEvents:UIControlEventTouchUpInside];
    [self.buttonOfLeft setBackgroundImage:[UIImage imageNamed:@"iconfont-fanhui-2"] forState:UIControlStateNormal];
    UIBarButtonItem *bar = [[UIBarButtonItem alloc] initWithCustomView:self.buttonOfLeft];
    self.navigationItem.leftBarButtonItem = bar;
    [bar release];
    
    [self handleData];
    
    [self createTableView];
}

#pragma mark - 判断网络状态
- (void)panDuanWangLuo {
    
    BOOL isExistenceNetwork = YES;
    Reachability *reach = [Reachability reachabilityForInternetConnection];
    
    switch ([reach currentReachabilityStatus]) {
        case NotReachable:{
            isExistenceNetwork = NO;
            NSLog(@"`````````网络不给力");
            
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"当前无网络" preferredStyle:UIAlertControllerStyleAlert];
            
            UIAlertAction *actionOK = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                
                
            }];
            
            [alert addAction:actionOK];
            
            [self presentViewController:alert animated:YES completion:^{
                
                
            }];
            
            break;
        }
        case ReachableViaWiFi:{
            isExistenceNetwork = YES;
            break;
        }
        case ReachableViaWWAN:{
            isExistenceNetwork = YES;
            break;
        }
    }
    
}

/** 处理数据 */
- (void)handleData {
    
    NSString *string = [NSString stringWithFormat:@"http://chanyouji.com/api/articles/%@.json?page=1", self.id];
    
    [NetworkingHandler networkingWithURL:string completeHandle:^(NSData *data,id result) {
        self.model = [[ModelOfClickZhuanTiCell alloc] init];
        
        self.model.name = [result objectForKey:@"name"];
        self.model.image_url = [result objectForKey:@"image_url"];
        self.model.title = [result objectForKey:@"title"];
        self.model.id = self.id;
        
        NSArray *arr = [result objectForKey:@"article_sections"];
        for (NSDictionary *dict in arr) {
            ModelForClickZTOfArticle *mode = [[ModelForClickZTOfArticle alloc] init];
            [mode setValuesForKeysWithDictionary:dict];
            [self.arrayOfModelForCell addObject:mode];
            
        }
       
        [self.tableView reloadData];
        
#pragma mark - 查询数据, 判断右侧收藏按钮样式
       BOOL is = [[DataBaseHandler shareDataBaseHandler] selectForName:self.model.name];
        if (is) {
            
            /** 主页navigation右侧button */
            self.buttonOfRight = [UIButton buttonWithType:UIButtonTypeCustom];
            self.buttonOfRight.frame = CGRectMake(300, 10, 26, 26);
            [self.buttonOfRight addTarget:self action:@selector(shouCang:) forControlEvents:UIControlEventTouchUpInside];
            [self.buttonOfRight setBackgroundImage:[UIImage imageNamed:@"yishoucang"] forState:UIControlStateNormal];
            self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithCustomView:self.buttonOfRight]autorelease];
            
        } else {
            
            /** 主页navigation右侧button */
            self.buttonOfRight = [UIButton buttonWithType:UIButtonTypeCustom];
            self.buttonOfRight.frame = CGRectMake(300, 10, 26, 26);
            [self.buttonOfRight addTarget:self action:@selector(shouCang:) forControlEvents:UIControlEventTouchUpInside];
            [self.buttonOfRight setBackgroundImage:[UIImage imageNamed:@"iconfont-shoucang-3"] forState:UIControlStateNormal];
            self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithCustomView:self.buttonOfRight]autorelease];
        }
    }];
    
#pragma mark - 推出照片界面
    [[NSNotificationCenter defaultCenter] addObserverForName:@"passPhoto" object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification * _Nonnull note) {
        
        VCOfPhoto *vc = [[VCOfPhoto alloc] init];
        vc.photo = [note.userInfo objectForKey:@"photo"];
        vc.note = [note.userInfo objectForKey:@"note"];
        vc.image_width = [note.userInfo objectForKey:@"image_width"];
        vc.image_height = [note.userInfo objectForKey:@"image_height"];
        [self.navigationController pushViewController:vc animated:YES];
     //   [vc release];
        
    }];
}

#pragma mark - 创建tableView
- (void)createTableView {
    
    self.tableView = [[UITableView alloc] initWithFrame:self.view.frame style:UITableViewStyleGrouped];
    [self.view addSubview:self.tableView];
    [_tableView release];
    self.tableView.showsVerticalScrollIndicator = NO;
    self.tableView.bounces = NO;
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.dk_backgroundColorPicker = DKColorWithRGB(0xffffff, 0x343434);

    [self.tableView registerClass:[HeaderOfClickZhuanTiCell class] forHeaderFooterViewReuseIdentifier:@"pool"];
    [self.tableView registerClass:[CellForClickZhuanTiCell class] forCellReuseIdentifier:@"pool1"];
    [self.tableView registerClass:[CellForClickZhuanTiCell2 class] forCellReuseIdentifier:@"pool2"];
}

#pragma mark - tableView协议方法
/** 返回头部view */
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    HeaderOfClickZhuanTiCell *view = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"pool"];
    [view passModel:self.model];
    
    return view;
}

/** 返回每个区cell行数 */
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.arrayOfModelForCell.count;
}

/** 返回cell */
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    ModelForClickZTOfArticle *model = [self.arrayOfModelForCell objectAtIndex:indexPath.row];
    
    if ([model.image_url isEqualToString:@""]) {
        
        CellForClickZhuanTiCell *cell = [tableView dequeueReusableCellWithIdentifier:@"pool1"];
        [cell passModel:model];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;                // cell选中风格
        cell.dk_backgroundColorPicker = DKColorWithRGB(0xffffff, 0x343434);

        return cell;
        
    } else {
        CellForClickZhuanTiCell2 *cell = [tableView dequeueReusableCellWithIdentifier:@"pool2"];
        
        [cell passModel:model];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.dk_backgroundColorPicker = DKColorWithRGB(0xffffff, 0x343434);

        return cell;
        
    }
}

/** 返回区头高度 */
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 180;
}

/** 返回cell高度 */
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    ModelForClickZTOfArticle *model = [self.arrayOfModelForCell objectAtIndex:indexPath.row];
    if ([model.image_url isEqualToString:@""]) {
        
        return [CellForClickZhuanTiCell heightForCell:model];
        
    } else {
        
        return [CellForClickZhuanTiCell2 heightForCell:model];
    }
    
}

#pragma mark - 左上角返回按钮
- (void)fanHui:(UIBarButtonItem *)button {
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - 右上角收藏按钮
- (void)shouCang:(UIBarButtonItem *)button {
    
    /** 查询数据. */
   BOOL is = [[DataBaseHandler shareDataBaseHandler] selectForName:self.model.name];
    
    if (is) {

        /** 主页navigation右侧button */
        self.buttonOfRight = [UIButton buttonWithType:UIButtonTypeCustom];
        self.buttonOfRight.frame = CGRectMake(300, 10, 26, 26);
        [self.buttonOfRight addTarget:self action:@selector(shouCang:) forControlEvents:UIControlEventTouchUpInside];
        [self.buttonOfRight setBackgroundImage:[UIImage imageNamed:@"iconfont-shoucang-3"] forState:UIControlStateNormal];
        self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithCustomView:self.buttonOfRight]autorelease];
        
        [[DataBaseHandler shareDataBaseHandler] deleteWithName:self.model.name];
        
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"收藏已取消" preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction *actionOK = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        
        [alert addAction:actionOK];
        
        [self presentViewController:alert animated:YES completion:^{
            
            
        }];
        
    } else {
        
        /** 插入数据 */
        [[DataBaseHandler shareDataBaseHandler] insertModel:self.model];
        
        [self.buttonOfRight setBackgroundImage:[UIImage imageNamed:@"yishoucang"] forState:UIControlStateNormal];

        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"已收藏" preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction *actionOK = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
            
        }];
     
        [alert addAction:actionOK];
        
        [self presentViewController:alert animated:YES completion:^{
            
            
        }];
 
    }
    
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
